pub(crate) mod application;
pub(crate) mod builder;
pub(crate) mod container;
mod extractor;
pub(crate) mod model;
mod peer;
pub(crate) mod prompt;
pub(crate) mod transform;
pub(crate) mod window;
mod workflow;

pub use extractor::*;
pub use peer::*;
pub use workflow::*;

use model_graph_types::{
    container::context::Context,
    database::{ConnectorProtocol, DataSource, DatabaseType},
    datasource::DataSourceProvider,
    modeling::{set_system_meta_database, system_meta_database},
};
use serde::{Serialize, Serializer};
use std::sync::{Arc, Mutex};

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Anyhow(#[from] anyhow::Error),
}

impl Serialize for Error {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.to_string().as_ref())
    }
}

pub type Result<T> = std::result::Result<T, Error>;

pub struct ContextState {
    context: Arc<Mutex<Context>>,
}

impl Default for ContextState {
    fn default() -> Self {
        let context = tauri::async_runtime::block_on(async move {
            let home_path =
                model_graph_common::utils::rrg01_home_path().expect("获取程序目录失败!");

            let url = format!(
                "sqlite:{}/rrg01.sqlite",
                home_path.to_str().expect("获取程序目录失败!")
            );

            tracing::debug!("ds:{}", url);

            let mut context = Context::default();
            //设置系统库
            set_system_meta_database(DataSource {
                database_type: DatabaseType::SQLite,
                protocol: ConnectorProtocol::SQLite,
                url: url,
                ..Default::default()
            })
            .expect("设置系统数据库失败!");

            context
                .set_default_datasource(system_meta_database().unwrap())
                .await
                .expect("设置默认数据源!");

            context
        });

        Self {
            context: Arc::new(Mutex::new(context)),
        }
    }
}
